<!--
-->
<template>
    <vxe-modal v-model="visible" :position="{top: '60px'}" :title="title" destroy-on-close  :min-width="layout.modalMinWidth(600)" resize show-footer show-maximize :width="layout.modalWidth(900)" :height="layout.modalHeight(700)" @close="cancelClick">
        <el-form ref="ELForm" v-loading="isLoading" :model="state.model" :rules="rules" :validate-on-rule-change="false" class="ELForm" inline label-width="120px">
            <el-form-item :style="layout.col2" label="账号" prop="userName">
                <el-input v-model="state.model.userName" />
            </el-form-item>
            <el-form-item :style="layout.col2" label="姓名" prop="realName">
                <el-input v-model="state.model.realName" />
            </el-form-item>
            <el-form-item :style="layout.col2" label="手机号" prop="phone">
                <el-input v-model="state.model.phone" :max="100" :min="0" style="width: 100%;text-align: left;" />
            </el-form-item>
            <el-form-item :style="layout.col2" label="邮箱" prop="email">
                <el-input v-model="state.model.email" autocomplete="off"/>
            </el-form-item>
            <el-form-item v-show="!state.model.id" :style="layout.col2" label="密码" prop="newPassword">
                <g-password-input v-model="state.model.newPassword"/>
            </el-form-item>
            <el-form-item v-show="!state.model.id" :style="layout.col2" label="确认密码" prop="repassword">
                <g-password-input v-model="state.model.repassword"/>
            </el-form-item>
            <el-form-item :style="layout.col2" label="当前组织" prop="sysOrgId">
                <el-tree-select v-model="state.model.sysOrgId" :check-strictly="true" :data="state.tree" :default-expand-all="true" :props="{label: 'name', children: 'children'}" :render-after-expand="false" style="width: 100%;" value-key="id" @change="onOrgChange" />
<!--                <el-text type="warning">只能选择科室</el-text>-->
            </el-form-item>
            <el-form-item :style="layout.col2" label="职位" prop="sysPostId">
                <el-select v-model="state.model.sysPostId" filterable>
                    <el-option v-for="item in state.postList" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item :style="layout.col2" label="性别" prop="gender">
                <el-radio-group v-model="state.model.gender">
                    <el-radio :value="1">男</el-radio>
                    <el-radio :value="2">女</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item :style="layout.col2" label="状态" prop="userStatus">
                <el-radio-group v-model="state.model.userStatus">
                    <el-radio :value="0">正常</el-radio>
                    <el-radio :value="1">停用</el-radio>
                    <el-radio :value="2">删除</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item :style="layout.col1" label="角色" prop="roleIds">
                <el-checkbox-group v-model="state.model.roleIds">
                    <el-checkbox v-for="item in state.roleList" :key="item.id" :value="item.id">{{ item.name }}</el-checkbox>
                </el-checkbox-group>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="cancelClick">取消</el-button>
            <el-button :loading="isSubmitting" type="primary" @click="beforeSubmit">
                确定
            </el-button>
        </template>
    </vxe-modal>
</template>

<script setup>
import {ref, reactive, computed, onMounted} from "vue";
import {FormMixins} from "@/utils/FormMixins";
import * as api from "./api.js";
import {checkPassword, checkPhone} from "@/utils/utils.js"

const {ELForm, visible, title, layout, isLoading, isSubmitting, state, setOptions, submitSuccess, cancelClick} = FormMixins();
const {$message} = window;

const Model = () => {
    return {
        id: 0,
        password: undefined,
        realName: undefined,
        headerImg: undefined,
        gender: 1,
        identityCard: undefined,
        phone: undefined,
        email: undefined,
        weChat: undefined,
        qYWeChat: undefined,
        userType: 0,
        sysOrgId: 0,
        sysPostId: 0,
        isAdmin: 0,
        userStatus: 0,
        userName: undefined,
        newPassword: undefined,
        repassword: undefined,
        roleIds: [],
        bureauId: null,
        areaCode: null,
    }
}

// 校验规则
const rules = computed(() => {
    return {
        userName: [{required: true, message: "请输入用户账号"}],
        realName: [{required: true, message: "请输入用户姓名"}],
        newPassword: state.model.id ? [] : [{required: true, validator: customRules.checkPassword}],
        repassword: state.model.id ? [] : [{required: true, validator: customRules.checkRepassword}],
        phone: [{required: true, validator: customRules.checkPhone}],
        // email: state.model.email ? [{type: "email", required: true, message: "请输入正确邮箱格式"}] : [{required: false, message: ""}],
        sysOrgId: [{required: true, message: "请选择组织"}],
        sysPostId: [{required: true, message: "请选择职位"}],
    }
})

// 自定义校验规则
const customRules = {
    // 自定义校验 密码
    checkPassword: (rule, value, callback) => {
        // if (!checkPassword(value)) return callback(new Error("密码不少于8位包含大小写、不连续数字、特殊字符"))
        if (!value||value.length<6) return callback(new Error("密码不少于6位字符"))
        return true;
    },
    // 自定义校验 确认密码
    checkRepassword: (rule, value, callback) => {
        if (!value || value.length < 6 || value !== state.model.newPassword) {
            return callback(new Error("请确认密码是否一致"));
        }
        return true;
    },
    // 自定义校验 手机号
    checkPhone: (rule, value, callback) => {
        if (!checkPhone(value)) {
            return callback(new Error("请输入正确的手机号"));
        }
        return true;
    },
};

// 组织切换
function onOrgChange(id, b) {
    console.log(b)
    const orgId = id;
    const org = state.tree.treeFind(item => item.id === id);

    // 单位 id 就是组织的 pid
    const pid = org.pid;
    const parent = state.tree.treeFind(item => item.id === pid);
    // 区划编号就是上级组织的区划编号
    let areaCode;
    if (parent) {
        areaCode = parent.areaCode;
    }
    state.model.bureauId = pid;
    state.model.areaCode = areaCode;
}

// 表单显示
async function show(config) {
    setOptions(config);
    state.model = Model();
    state.model = {...state.model, ...state.options}
    // 初始化数据
    if (state.model.id) {
        api.GetUserInfoById({userId: state.model.id}).then(({data}) => {
            if (data) {
                state.model = {...state.model, ...data}
            }
        })
    }

    // 查询组织树
    api.GetOrgTreeList().then(({success, data}) => {
        if (success) {
            state.tree = data;
            state.tree.treeMap(item => {
                // item.disabled = item.orgType === 1;
                return item;
            });
        }
    });
    //  查询职位列表
    api.GetPostList().then(({success, data}) => {
        if (success) {
            state.postList = data;
        }
    })
    // 查询角色列表
    api.GetRoleList().then(({success, data}) => {
        if (success) {
            state.roleList = data;
        }
    })

}

// 校验表单
function beforeSubmit() {
    ELForm.value.validate(isOk => {
        isOk && submit()
    })
}

// 提交表单
async function submit() {
    isSubmitting.value = true
    console.log("submit: ", state.model)
    const body = {...state.model}
    // if (body.orgIds.findIndex(id => id === state.model.sysOrgId) < 0) {
    //     body.orgIds.push(state.model.sysOrgId)
    // }
    console.log("用户信息: ", JSON.stringify(body))
    const {success, data} = await api[state.model.id ? 'UpdateUserInfo' : 'AddUserInfo'](body);
    isSubmitting.value = false
    if (!success) return 0;
    $message.success("操作成功")
    submitSuccess()
}

onMounted(() => {
})
defineExpose({
    show
})
</script>


<style lang="scss" scoped>
.EditForm {

}
</style>
